package com.example.demo.controller;


import com.example.demo.utils.ExcuteLinux;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;


@RequestMapping("/file")
@Slf4j
@RestController
public class FileController {

    @Value("${file.upload.dir}")
    private String uploadFilePath;
    @Value("${file.download.dir}")
    private String downloadFilePath;
    @Value("${file.download.process}")
    private String downloadProcess;

    //执行linux命令
    private ExcuteLinux excuteLinux;

    @PostMapping("/uploadFile")
    public void fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        JSONObject result = new JSONObject();
        if (file.isEmpty()) {
//            result.put("error", "空文件!");
//            return result.toString();
            return;
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = file.getClass().getResource("").getPath();
        System.out.println("filePath: " + filePath);
        log.info("上传文件名称为:{}, 后缀名为:{}!", fileName, suffixName);

        File fileTempObj = new File(uploadFilePath + "/" + fileName);
        System.out.println(uploadFilePath);

        // 检测目录是否存在
        if (!fileTempObj.getParentFile().exists()) {
            fileTempObj.getParentFile().mkdirs();
        }
        // 使用文件名称检测文件是否已经存在
//        if (fileTempObj.exists()) {
//            result.put("error", "文件已经存在!");
//            return result.toString();
//        }

        try {
            // 写入文件:方式1
            file.transferTo(fileTempObj);
            // 写入文件:方式2
            //cn.hutool.core.io.FileUtil.writeBytes(file.getBytes(), fileTempObj);
        } catch (Exception e) {
//            log.error("发生错误: {}", e);
//            result.put("error", e.getMessage());
//            return result.toString();
            return;
        }

//        String z = fileName.substring(0,fileName.length()-4);
//        System.out.println(z);
//        String newpath = "D:\\Desktop\\test\\demo6\\test\\"+ z +"\\2.xml";
//        String oldpath = "D:\\Desktop\\test\\demo6\\"+ fileName;
//        System.out.println("new:"+ newpath);
//        System.out.println("old:"+ oldpath);
//        if (!oldpath.equals(newpath)) {
//            File oldfile = new File(oldpath);
//            File newfile = new File(newpath);
//            if (oldfile.exists()) {
//                oldfile.renameTo(newfile);
//            }
//        } else
//            System.out.println("文件不存在！");
//        result.put("success", "文件上传成功!");
//        return result.toString();
    }


    /**
     * 多个文件上传
     *
     * @param files
     * @return
     * @throws JSONException
     */
    @ResponseBody
    @PostMapping("/uploadFiles")
    public String fileUploads(@RequestParam("files") MultipartFile files[]) throws JSONException {
        JSONObject result = new JSONObject();

        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();
            File dest = new File(uploadFilePath + '/' + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
            } catch (Exception e) {
                log.error("发生错误: {}", e);
                result.put("error", e.getMessage());
                return result.toString();
            }
        }
        result.put("success", "文件上传成功!");
        return result.toString();
    }

    // 下载到了默认的位置
//     @ResponseBody
//     @GetMapping("/downloadFile/progress")
//     public String progrsssDownload(HttpServletResponse response, @RequestParam("fileName") String fileName) throws JSONException, IOException {
//        JSONObject result = new JSONObject();
//
//        File file = new File(uploadFilePath + '/' + fileName);
//         System.out.println(uploadFilePath);
//        if (!file.exists()) {
//            result.put("error", "下载文件不存在!");
//            return result.toString();
//        }
//
//        response.reset();
//        response.setContentType("application/octet-stream");
//        response.setCharacterEncoding("utf-8");
//        response.setContentLength((int) file.length());
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//
//        // 原生的方式
//         try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
//             byte[] buff = new byte[1024];
//             OutputStream os = response.getOutputStream();
//             int i = 0;
//             while ((i = bis.read(buff)) != -1) {
//                 os.write(buff, 0, i);
//                 os.flush();
//             }
//         } catch (IOException e) {
//             log.error("发生错误: {}", e);
//             result.put("error", e.getMessage());
//             return result.toString();
//         }
        // 简单方式: 方式1
        // byte[] bytes = FileCopyUtils.copyToByteArray(file);
        // 简单方式: 方式2
//        byte[] readBytes = cn.hutool.core.io.FileUtil.readBytes(file);
//        OutputStream os = response.getOutputStream();
//        os.write(readBytes);
//        result.put("success", "下载成功!");
//        return result.toString();
//    }

    @ResponseBody
    @GetMapping("/downloadFile")
    public String fileDownload(HttpServletResponse response, @RequestParam(value="fileName") String fileName) throws JSONException, IOException {
        System.out.println("filename:"+fileName);
        JSONObject result = new JSONObject();

        String taskDir = fileName.substring(0,fileName.lastIndexOf("."));
        String dataTarget = "/home/unicom/tongyijiemian/java_sub6G/Sub6G/sim_data";
        excuteLinux.exeCmd("cd /home/unicom/tongyijiemian/java_sub6G/Sub6G"+"/"+ taskDir +" && "+"zip -r "+fileName+" "+"outputfiles");
        System.out.println(taskDir+":输出数据压缩完成");
        excuteLinux.exeCmd("cp -a /home/unicom/tongyijiemian/java_sub6G/Sub6G"+"/"+ taskDir+"/"+fileName+" "+dataTarget);

        File file = new File(downloadFilePath + '/' + fileName);
        System.out.println("downloadFilePath:"+downloadFilePath);
        if (!file.exists()) {
            result.put("error", "下载文件不存在!");
            return result.toString();
        }
        //读入要下载的文件，保存到文件输入流
        FileInputStream in = null;
        //创建输出流
        OutputStream out = null;

        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        //设置响应头，控制浏览器下载该文件
        response.setHeader( "Content-Disposition", "attachment;filename=" + fileName);

        try {
            //读取要下载的文件，保存到文件输入流
            in= new FileInputStream(file.getPath());
            //创建输出流
            out= response.getOutputStream();
            //缓存区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区中
            while((len = in.read(buffer)) > 0){
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            log.error("发生错误: {}", e);
            result.put("error", e.getMessage());
            return result.toString();
        }finally {
            //关闭
            in.close();
            out.close();
        }
        result.put("success", "下载成功!");
        return result.toString();
    }

    @ResponseBody
    @GetMapping("/downloadProcess")
    public String processFileDownload(HttpServletResponse response, @RequestParam(value="fileName") String fileName,@RequestParam(value="parentDir") String parentDir) throws JSONException, IOException {
        System.out.println("filename:"+fileName);
        JSONObject result = new JSONObject();

        File file = new File(downloadProcess + '/' +parentDir + '/' + fileName);
//        System.out.println("downloadFilePath:"+downloadFilePath);
        if (!file.exists()) {
            result.put("error", "下载文件不存在!");
            return result.toString();
        }
        //读入要下载的文件，保存到文件输入流
        FileInputStream in = null;
        //创建输出流
        OutputStream out = null;

        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        //设置响应头，控制浏览器下载该文件
        response.setHeader( "Content-Disposition", "attachment;filename=" + fileName);

        try {
            //读取要下载的文件，保存到文件输入流
            in= new FileInputStream(file.getPath());
            //创建输出流
            out= response.getOutputStream();
            //缓存区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区中
            while((len = in.read(buffer)) > 0){
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            log.error("发生错误: {}", e);
            result.put("error", e.getMessage());
            return result.toString();
        }finally {
            //关闭
            in.close();
            out.close();
        }
        result.put("success", "下载成功!");
        return result.toString();
    }

        // 原生的方式
//        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
//            byte[] buff = new byte[1024];
//            OutputStream os = response.getOutputStream();
//            int i = 0;
//            while ((i = bis.read(buff)) != -1) {
//                os.write(buff, 0, i);
//                os.flush();
//            }
//        } catch (IOException e) {
//            log.error("发生错误: {}", e);
//            result.put("error", e.getMessage());
//            return result.toString();
//        }
        // 简单方式: 方式1
        // byte[] bytes = FileCopyUtils.copyToByteArray(file);
        // 简单方式: 方式2
//        byte[] readBytes = cn.hutool.core.io.FileUtil.readBytes(file);
//        OutputStream os = response.getOutputStream();
//        os.write(readBytes);


    // 下载到了默认的位置
//    @ResponseBody
//    @GetMapping("/downloadFile")
//    public ResponseEntity<byte[]> downloadFolder(Long businessId) throws IOException {
//        ResponseEntity<byte[]> response = null;
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//        headers.add("Content-Disposition", "attachment; filename=spark-warehouse.zip");
//        headers.add("Pragma", "no-cache");
//        headers.add("Expires", "0");
//        headers.add("Content-Language", "UTF-8");
//        ByteArrayOutputStream zos =
//                (ByteArrayOutputStream) hdfsClientService.down2("hdfs://172.16.1.9:8020/spark/spark-warehouse");
//        byte[] out = zos.toByteArray();
//        zos.close();
//        response = new ResponseEntity<>(out, headers, HttpStatus.OK);
//
//        return response;
//    }
//
//    public OutputStream down2(String cloudPath) {
//        // 1获取对象
//        ByteArrayOutputStream out = null;
//        try {
//            Configuration conf = new Configuration();
//            FileSystem fs = FileSystem.get(new URI("hdfs://172.16.1.9:8020"), conf);
//            out = new ByteArrayOutputStream();
//            ZipOutputStream zos = new ZipOutputStream(out);
//            compress(cloudPath, zos, fs);
//            zos.close();
//        } catch (IOException e) {
//            log.info("----error:{}----" + e.getMessage());
//        } catch (URISyntaxException e) {
//            log.info("----error:{}----" + e.getMessage());
//        }
//        return out;
//    }
//    public void compress(String baseDir, ZipOutputStream zipOutputStream, FileSystem fs) throws IOException {
//
//        try {
//            FileStatus[] fileStatulist = fs.listStatus(new Path(baseDir));
//            log.info("basedir = " + baseDir);
//            String[] strs = baseDir.split("/");
//            //lastName代表路径最后的单词
//            String lastName = strs[strs.length - 1];
//
//            for (int i = 0; i < fileStatulist.length; i++) {
//
//                String name = fileStatulist[i].getPath().toString();
//                name = name.substring(name.indexOf("/" + lastName));
//
//                if (fileStatulist[i].isFile()) {
//                    Path path = fileStatulist[i].getPath();
//                    FSDataInputStream inputStream = fs.open(path);
//                    zipOutputStream.putNextEntry(new ZipEntry(name.substring(1)));
//                    IOUtils.copyBytes(inputStream, zipOutputStream, Integer.parseInt("1024"));
//                    inputStream.close();
//                } else {
//                    zipOutputStream.putNextEntry(new ZipEntry(fileStatulist[i].getPath().getName() + "/"));
//                    log.info("fileStatulist[i].getPath().toString() = " + fileStatulist[i].getPath().toString());
//                    compress(fileStatulist[i].getPath().toString(), zipOutputStream, fs);
//                }
//            }
//        } catch (IOException e) {
//            log.info("----error:{}----" + e.getMessage());
//        }
//    }

}


